//
//  ETEnReq.m
//  etradekd
//
//  Created by jacknan on 2022/2/23.
//  Copyright © 2022 UPBest. All rights reserved.
//

#import "ETEnReq.h"

@implementation ETEnReq

+ (NSMutableURLRequest *)en:(NSMutableURLRequest *)req {
    NSString *accessToken = MNNETWORK.accessToken;
    NSString *tokenType = MNNETWORK.tokenType;
    NSDictionary *bodyDic = [NSJSONSerialization JSONObjectWithData:req.HTTPBody options:NSJSONReadingAllowFragments error:nil];
    NSString *bodyStr = bodyDic.mj_JSONString;
    NSString *pk = @"041593c0721374671edaf090544bd5a61a11afbf762bed2f8c2d00966a601a3623b5aff19b001a5e7cdfbc2e4f5b770562b8e7c602418c712fce974c87a4e45752";
//    NSLog(@"body明文:%@", bodyStr);
//    NSLog(@"accessToken:%@", accessToken);
    
    
    NSString *timestamp = [NSString stringWithFormat:@"%ld",(NSInteger)[NSDate.date timeIntervalSince1970]*1000];
    NSLog(@"timestamp:%@", timestamp);
    
    NSString *Authorization = [NSString stringWithFormat:@"%@ %@", tokenType, accessToken];
    if (accessToken && bodyStr && timestamp) {
        NSString *signature = [self sort:@[accessToken, bodyStr, timestamp]];
    //    NSLog(@"SM3(sort(access token + body 明文 + timestamp)):%@",signature)
        
        NSString *sm2Signature = [GMSm2Utils encryptText:signature publicKey:pk];
        sm2Signature = [NSString stringWithFormat:@"04%@",[GMSm2Utils asn1DecodeToC1C3C2:sm2Signature].lowercaseString];
    //    NSLog(@"公钥加密后最终signature:%@", sm2Signature);
        
        bodyStr = [NSString stringWithFormat:@"%@%@", sm2Signature, bodyStr];
    //    NSLog(@"sm2(signature)+明文body:%@", bodyStr);
        
        bodyStr = [GMSm4Utils cbcEncryptText:bodyStr key:@"f1b6d833fe6cddc37e5e0dda6fc0d878" IV:@"bb6654352d7e95c56895ba229b871996"].lowercaseString;
    //    NSLog(@"sm4(sm2(signature)+明文body):%@", bodyStr);
        NSMutableURLRequest *newReq = [[AFHTTPRequestSerializer serializer] requestWithMethod:req.HTTPMethod URLString:req.URL.absoluteString parameters:nil error:nil];
        [req.allHTTPHeaderFields enumerateKeysAndObjectsUsingBlock:^(NSString * _Nonnull key, NSString * _Nonnull obj, BOOL * _Nonnull stop) {
            [newReq setValue:obj forHTTPHeaderField:key];
        }];
        [newReq setValue:@"text/plain" forHTTPHeaderField:@"Content-Type"];
        [newReq setValue:timestamp forHTTPHeaderField:@"timestamp"];
        if (!ISXN) {
            [newReq setValue:Authorization forHTTPHeaderField:@"Authorization"];
        }
        [newReq setValue:sm2Signature forHTTPHeaderField:@"signature"];
        [newReq setHTTPBody:[NSString stringWithFormat:@"%@",bodyStr].dataValue];
        return newReq;
    }else{
        return req;
    }
}

+ (NSString *)sort:(NSArray *)strArr {
    NSArray *arr = [strArr sortedArrayUsingComparator:^NSComparisonResult(NSString *obj1, NSString *obj2) {
        return [obj1 compare:obj2] == NSOrderedDescending;
    }];
    NSMutableString *str = NSMutableString.string;
    for (int i=0; i<arr.count; i++) {
        [str appendString:arr[i]];
    }
//    NSLog(@"sort(accesstoken+body明文+timestamp):%@", str);
    return [GMSm3Utils hashWithString:str].lowercaseString;
}

@end

@implementation ETApiTokenReq
- (instancetype)init
{
    self = [super init];
    if (self) {
        self.noEncrypt = YES;
        self.appid = @"yzKjgIkIZCs4ZeCcgqH5R";
        self.nonce = [NSString stringWithFormat:@"%d",arc4random()%100];
        self.timestamp = [NSString stringWithFormat:@"%ld",(NSInteger)[NSDate.date timeIntervalSince1970]*1000];
        self.grant_type = @"client_credentials";
        NSString *appsecret = @"btXBagwZnPWDsDxyfLESgddiYwxcnDmtQcpp";
        self.signature = [ETEnReq sort:@[self.timestamp, self.nonce, self.appid, appsecret]];
        self.reqUrl = [NSString stringWithFormat:@"%@%@?appid=%@&nonce=%@&timestamp=%@&signature=%@&grant_type=%@", BASEURL, self.routingPath, _appid, _nonce, _timestamp, _signature, _grant_type];
    }
    return self;
}

- (ReqMethod)method {
    return ReqMethodPost;
}

- (NSString *)routingPath {
    return @"/px-common-defense/oauth/token";
}
@end
